package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
    //订单
    @Autowired
    private OrderService orderService;
    //订单明细
    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 修改状态成功
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders orders){
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Orders::getId,orders.getId());
        wrapper.set(Orders::getStatus,orders.getStatus());
        orderService.update(wrapper);
        return R.success("修改成功");


    }
    /**
     * 查询管理端订单明细
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String number,
                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String beginTime,
                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime
    ) {
        //封装
        Page<Orders> orderPageInfo = new Page<>(page, pageSize);
        //创建订单条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        //模糊查询
        wrapper.like(number != null, Orders::getNumber, number);
        //查询时间范围
        wrapper.between((beginTime!=null)&&(endTime!=null),Orders::getOrderTime, beginTime, endTime);
        //条件排序
        wrapper.orderByAsc(Orders::getCheckoutTime);
        //查询的下单时间大于开始时间
        //wrapper.ge(startTime != null, Orders::getOrderTime, startTime);
        //查询的下单时间小于结束时间
        //wrapper.le(endTime != null, Orders::getOrderTime, endTime);
        //调用方法
        orderService.page(orderPageInfo, wrapper);
        return R.success(orderPageInfo);
    }

    /**
     * 移动端最新（历史）订单明细
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(Integer page, Integer pageSize) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        //封装
        Page<Orders> ordersPageInfo = new Page<>(page, pageSize);
        //创建dto封装对象
        Page<OrderDto> orderDtoPageInfo = new Page<>();
        //创建订单条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        //查询用户id
        wrapper.eq(Orders::getUserId, userId);
        //条件：根据下单时间排序
        wrapper.orderByAsc(Orders::getOrderTime);
        //根据条件分页查询
        orderService.page(ordersPageInfo, wrapper);
        //拷贝数据到dto层
        BeanUtils.copyProperties(ordersPageInfo, orderDtoPageInfo, "records");
        //获取当前页数据
        List<Orders> ordersList = ordersPageInfo.getRecords();
        ArrayList<OrderDto> orderDtosList = new ArrayList<>();
        for (Orders orders : ordersList) {
            //创建dto层对象
            OrderDto orderDto = new OrderDto();
            //创建明细表条件构造器
            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            //条件：查询订单id
            orderDetailWrapper.eq(OrderDetail::getOrderId, orders.getId());
            //查询所有订单明细数据
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailWrapper);
            //将查询到的订单明细数据赋值给dto
            orderDto.setOrderDetails(orderDetailList);
            //拷贝数据
            BeanUtils.copyProperties(orders, orderDto);
            //添加数据到dto
            orderDtosList.add(orderDto);
        }
        orderDtoPageInfo.setRecords(orderDtosList);
        return R.success(orderDtoPageInfo);
    }

    /**
     * 下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("请求提交的订单：{}", orders.toString());
        orderService.submit(orders);
        return R.success("下单成功，等待骑手接单~");
    }
}
